<?php
declare (strict_types=1);

namespace app\admin\controller;


use app\common\builder\TableBuilder;
use app\common\builder\TableFront;
use app\common\model\Area;
use app\common\model\OrderLogistics;
use app\common\model\OrderProduct;
use think\App;
use think\exception\ValidateException;
use think\facade\View;
use app\common\model\ProductCate;
use think\response\Json;

class Order extends Base
{

    //主键，默认为id
    protected $pk = 'id';

    //主模型
    protected $model = '\app\common\model\Order';

    //搜索条件
    protected $search;

    //关联模型
    protected $hasOne = ['user', 'address', 'express', 'p', 'c', 'd','business'];

    protected $append = ['return_text'];

    //页面所需表头参数，渲染相关参数参考layui官方文档，目前暂时为静态，后期考虑存库
    protected $table;


    public function index()
    {
        return $this->setTable();
    }

    public function setTable()
    {
        //构建table
        $tableFront = TableFront::getInstance()
            ->addRow(['type' => 'checkbox', 'fixed' => 'left', 'title' => '全选'])
            ->addRow(['field' => 'id', 'title' => '订单ID', 'width' => 90])
            ->addRow(['field' => 'sn', 'title' => '订单编号', 'width' => 220])
            ->addRow(['field' => 'business_title', 'title' => '所属商家', 'templet' => '<div>{{d.business?d.business.title:"【未支付】"}}</div>'])
            ->addRow(['field' => 'product_info', 'title' => '订单商品', 'width' => 800])
            ->addRow(['field' => 'total_amount', 'title' => '订单金额'])
            ->addRow(['field' => 'status', 'title' => '订单状态'])
            ->addRow(['field' => 'real_amount', 'title' => '实付金额'])
            ->addRow(['field' => 'cost', 'title' => '成本'])
            //->addRow(['field' => 'profit', 'title' => '订单总利润'])
            //->addRow(['field' => 'vip_profit', 'title' => 'vip积分总利润'])
            ->addRow(['field' => 'code', 'title' => '下单会员', 'templet' => '<div>{{d.user.code}}</div>'])
            ->addRow(['field' => 'create_time', 'title' => '下单时间'])
            ->addRow(['field' => 'pay_time', 'title' => '支付时间'])
            ->addRow(['field' => 'pay_way', 'title' => '支付方式'])
            //->addRow(['field' => 'currency', 'title' => '爱贝总抵扣金额'])
            //->addRow(['field' => 'chain_bean', 'title' => '链豆总抵扣金额'])
            //->addRow(['field' => 'love_bean', 'title' => '爱豆总抵扣金额'])
            //->addRow(['field' => 'vip_integ', 'title' => 'VIP积分总抵扣金额'])
            //->addRow(['field' => 'red_coin', 'title' => '积分总抵扣金额'])
            //->addRow(['field' => 'deduct', 'title' => '抵扣券总抵扣金额'])
            ->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 250]);

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addTopButtons(['deleteAll', 'export'])
            ->setSearch($this->setSearch())
            ->addJsUrl(['order'])
            ->fetch('order/index');
    }

    public function setSearch()
    {
        return TableFront::getInstance()
            ->setSearch(['uid', '会员编号/昵称/手机号', 'input', '', '\app\common\model\User', 'code|nickname|mobile,id'])
            ->setSearch(['business_id', '商家名称', 'input', '', '\app\common\model\Business', 'title,id'])
            ->setSearch(['product_info', '商品名称', 'input'])
            ->setSearch(['sn', '订单编号', 'input'])
            ->setSearch(['status', '订单状态', 'select', getOrderStatus('', 2)]);
    }


    public function getList($takeOver = true): Json
    {
        return parent::getList($takeOver); // TODO: Change the autogenerated stub
    }

    public function edit($name = '', $id = '', $tpl = 'order/edit', $info = '')
    {
        $info = $this->model::find($id);

        return parent::edit($name, $id, $tpl, $info); // TODO: Change the autogenerated stub
    }


    public function deliver($id = '')
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            try {
                $this->validate($param, 'Deliver');
            } catch (ValidateException $e) {
                return json(['code' => -1, 'msg' => $e->getError()]);
            }
            return json($this->model::deliver($param, $this->admin));
        }

        $info = $this->model::find($id);

        if($delivered_pids = OrderLogistics::where('order_id', $id)->column('product_ids')){
            $products = OrderProduct::where('order_id', $id)->whereNotIn('pid', implode(',', $delivered_pids))->select();
        }else{
            $products = OrderProduct::where('order_id', $id)->select();
        }

        View::assign([
            'express' => \app\common\model\Express::where(['status' => 1, 'is_del' => 0])->select(),
            'info' => $info,
            'products' => $products
        ]);
        return View::fetch();
    }

    public function delivered($id = '')
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['product_ids'] = true;
            try {
                $this->validate($param, 'Deliver');
            } catch (ValidateException $e) {
                return json(['code' => -1, 'msg' => $e->getError()]);
            }
            return json($this->model::delivered($param, $this->admin));
        }

        $info = $this->model::find($id);

        $logistics = OrderLogistics::where('order_id', $id)->append(['products'])->select();

        View::assign([
            'express' => \app\common\model\Express::where(['status' => 1, 'is_del' => 0])->select(),
            'info' => $info,
            'logistics' => $logistics
        ]);
        return View::fetch();
    }


    public function export()
    {
        $name = '订单列表' . date('Y-m-d H:i:s');
        $s = $this->setMap($this->request->get('name'));


        $title = TableFront::getInstance()->getFieldTable($this->request->get('name'));
        if (empty($title)) {
            return json(['code' => -1, 'msg' => '导出失败，请清除缓存后重试！']);
        }
        $add = [
            'receiver' => '收货人',
            'receiver_tel' => '收货电话',
            'post_address' => '收货地址',
            'express_title' => '快递公司',
            'express_code' => '快递单号',
            'post_time' => '发货时间',
            'currency' => '爱贝总抵扣金额',
            'chain_bean' => '链豆总抵扣金额',
            'love_bean' => '爱豆总抵扣金额',
            'vip_integ' => 'vip积分总抵扣金额',
            'red_coin' => '红包币总抵扣金额',
            'deduct' => '抵扣券总抵扣金额',
        ];
        $title = array_merge($title, $add);
        $unset = [];
        foreach ($title as $key => $item) {
            $unset[] = $key;
        }
        $s['filed'] = '*';
        $list = $this->model::_all($s['map'], $s['param'], $this->hasOne, $s['like'], 'create_time,desc', [], $s['filed'], true);
        $data = [];
        foreach ($list['data'][0]->toArray() as $key => $item) {
            $data[] = $key;
        }

        $diff = array_diff($data, $unset);

        foreach ($list['data'] as &$v) {
            if($v->is_return) $v->status = '已退款';
            $v['code'] = $v->user->code;
            $v['express_title'] = $v->express ? $v->express->title : '';
            $v['business_title'] = isset($v['business']) ? $v['business']['title'] : '未支付';
            $v['post_address'] = Area::where('code', $v['district'])->value('concat_ws("", province,city,district) as title').$v['address_details'];
            $v['post_time'] = $v['post_time'] ?date("Y-m-d H:i:s", $v['post_time']) : '-';
            foreach ($diff as $item) {
                unset($v->$item);
            }

        }

        return json(['code' => 1, 'result' => ['data' => $list['data']->toArray(), 'title' => $title, 'name' => $name]]);
    }


    public function getArea($id, $level = 0)
    {
        return Area::getArea($id ?: 100000, $level);
    }

}
